package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.constant.CommunityConstant;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.AliOssUtil;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 花木凋零成兰
 * @date 2024/3/10 19:48
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private UserService userService;

    @Resource
    private HostHolder hostHolder;

    @Resource
    private LikeService likeService;

    @Resource
    private FollowService followService;

    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 获取修改用户信息界面
     * @return
     */
    @LoginRequired
    @GetMapping(path = "/setting")
    public String getSettingPage() {
        log.warn("setting...");
        return "/site/setting";
    }

    /**
     * 用户上传文件   (改用云服务)
     * @param headerImage
     * @param model
     * @return
     */
    @LoginRequired
    // SpringMvc 通过MultipartFile处理上传文件
    @PostMapping("/upload")
    public String uploadHeader(MultipartFile headerImage, Model model) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }
        String fileName = headerImage.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));  // 获取文件后缀
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件的格式不正确!");
        }
        // 生成随机文件名
        fileName = CommunityUtil.generateUUID() + suffix;
        // 确定文件存放的路径
        // File dest = new File(uploadPath + "/" + fileName);
        try {
            // headerImage.transferTo(dest);
            fileName = aliOssUtil.upload(headerImage.getBytes(), fileName);
        } catch (IOException e) {
            log.error("上传文件失败：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生异常!", e);
        }
        // 更新当前用户的头像的路径(web 访问路径)
        // http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        // String headerUrl = domain + contextPath + "/user/header/" + fileName;
        String headerUrl = fileName;    // 改用阿里云
        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    /**
     * 获取用户头像
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        // 服务器存放路径
        fileName = uploadPath + "/" + fileName;
        // 确定文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        // 响应图片
        response.setContentType("image" + suffix);  // 设置响应类型
        try (
                OutputStream os = response.getOutputStream();
                FileInputStream fileInputStream = new FileInputStream(fileName);
                ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fileInputStream.read(buffer)) != -1)  {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            log.error("读取头像失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户修改密码
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(path = "/update", method = RequestMethod.POST)
    public String updatePassword(String oldPassword, String newPassword, String confirmPassword,
                                 Model model, HttpServletRequest request) {
        // 判断是否输入原密码
        if (oldPassword == null) {
            model.addAttribute("oldPasswordMsg", "原密码不能为空!");
            return "/site/setting";
        }
        // 判断新密码是否为空
        if (newPassword == null) {
            model.addAttribute("newPasswordMsg", "新密码不能为空!");
            return "/site/setting";
        }
        // 判断确认密码是否为空
        if (confirmPassword == null) {
            model.addAttribute("confirmPasswordMsg", "确认密码不能为空!");
        }
        // 获取当前登录用户信息
        User user = hostHolder.getUser();
        // 判断原密码是否正确
        oldPassword = CommunityUtil.md5(oldPassword + user.getSalt());
        if (!user.getPassword().equals(oldPassword)) {
            model.addAttribute("oldPasswordMsg", "原密码不正确!");
            return "/site/setting";
        }
        // 判断新密码 与 确认密码 是否一致
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("confirmPasswordMsg", "确认密码与新密码不一致!");
            return "/site/setting";
        }
        // 更新salt
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));
        // 对新密码进行md5加密
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        // 修改密码
        userService.updatePassword(user.getId(), newPassword, user.getSalt());
        // 修改密码后 用户应该自主退出登录状态 并跳转到重新登录界面
        // 从cookie中获取ticket
        String ticket = CookieUtil.getValue(request, "ticket");
        userService.logout(ticket); // 退出登录
        model.addAttribute("msg", "修改密码成功，请重新登录!");
        model.addAttribute("target", "/login");
        return "/site/operate-result";
    }

    /**
     * 用户个人主页
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, CommunityConstant.ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(CommunityConstant.ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);

        // 是否已关注某用户
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), CommunityConstant.ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);
        model.addAttribute("myId", hostHolder.getUser().getId());

        return "site/profile";
    }

//    @RequestMapping(path = "/post/{userId}", method = RequestMethod.GET)
//    public String getUserPost(Model, ) {
//
//    }

}
